package com.hrt.common.safe;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.btcode.web.core.unit.WebContext;
import com.hrt.common.safe.token.TokenService;
import com.hrt.common.web.RequestUnit;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 登录用户session管理器
 *
 * @author gislin
 */
public final class UserSessionManager {

    private static UserSessionManager instance;

    ILog log;

    private UserSessionManager() {
        log = MyLog.getInstance().getLogger(UserSessionManager.class);
    }

    public static UserSessionManager getInstance() {

        if (instance == null) {
            synchronized (UserSessionManager.class) {
                if (instance == null) {
                    instance = new UserSessionManager();
                    return instance;
                }
            }
        }
        return instance;
    }

    public void setUser(IUser user) {

        WebContext.getSession().setAttribute("userInfo", user);
    }

    public void clearUser() {

        WebContext.getSession().removeAttribute("userInfo");
    }

    /**
     * 先从session中，获取用户信息 如果没有，则尝试获取请求中的_token信息,通过_token反算用户信息
     */
    public IUser getUser() {

        Object obj = WebContext.getSession().getAttribute("userInfo");
        if (obj != null && obj instanceof IUser) {
            return (IUser) obj;
        }
        IUser user = null;
        String token = RequestUnit.getString("_token");
        if (token == null || token.trim().equals("")) {
            HttpServletRequest resq = WebContext.getRequest();
            // 文件上传接口的token 单独设置在heda里。
             token= resq.getHeader("FILETOKEN");
            if (token == null || token.trim().equals("")) {
                return null;
            }
        }
        try {
            user = TokenService.decodeToken(token);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("token解析出错",e);
        }
        return user;
    }
}
